<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\GoodsModel;
use support\Request;
use support\Response;
use plugin\admin\app\model\GoodsAttr;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 商品属性 
 */
class GoodsAttrController extends Crud
{
    
    /**
     * @var GoodsAttr
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new GoodsAttr;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('goods-attr/index');
    }

    public function attrs(Request $request): Response
    {
        $modelId = $request->post('model_id');

        $attrs = GoodsAttr::where('model_id', $modelId)->orderBy('sort')->get()->toArray();

        $html = '<table class="layui-table">';

        $html .= '<tr><th>属性</th><th>属性值</th></tr>';

        foreach ($attrs as $attr) {
            $html .= <<< EOF
            <tr>
                <td>{$attr['name']}</td>
                <td><input type="text" name="attr[{$attr['id']}]" value="" class="layui-input"></td></td>
            </tr>
EOF;

        }

        $html .= '</table>';

        return json(['code' => 0, 'msg' => 'ok', 'data' => $html]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('goods-attr/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('goods-attr/update');
    }

    protected function formatNormal($items, $total): Response
    {
        $models = GoodsModel::list();
        $models = array_combine(
            array_column($models, 'value'),
            array_values($models)
        );

        foreach ($items as $key=>$item) {
            $items[$key]['model_text'] = $models[$item['model_id']]['name'];
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
